package com.moji.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moji.common.entity.MyPage;
import com.moji.common.utils.PageUtil;
import com.moji.entity.*;
import com.moji.entity.dto.CompleteBillDto;
import com.moji.entity.dto.QueryBillDto;
import com.moji.entity.vo.MjBillVo;
import com.moji.mapper.MjBillMapper;
import com.moji.service.*;
import com.moji.util.DateUtils;
import com.moji.util.IdGenerator;
import com.moji.util.MoJiCommonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 发票表 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2024-08-21
 */
@Service
public class MjBillServiceImpl extends ServiceImpl<MjBillMapper, MjBill> implements MjBillService {

    @Resource
    private MjOrderService mjOrderService;

    @Resource
    private SysMessageService sysMessageService;

    @Resource
    private MjUserService mjUserService;

    @Resource
    private GdAreaService gdAreaService;

    @Resource
    private IdGenerator idGenerator;

    @Override
    public MyPage<MjBill> queryByPage(QueryBillDto dto) {
        LambdaQueryWrapper<MjBill> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(dto.getUserName()),MjBill::getUserName
                ,dto.getUserName());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getOrderCode()),MjBill::getOrderCode
                ,dto.getOrderCode());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getOrderName()),MjBill::getOrderName
                ,dto.getOrderName());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getBillStatus()),MjBill::getBillStatus
                ,dto.getBillStatus());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getMobile()),MjBill::getMobile
                ,dto.getMobile());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getPayAmount()),MjBill::getPayAmount
                ,dto.getPayAmount());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getPayType()),MjBill::getPayType
                ,dto.getPayType());
        //创建时间倒叙
        wrapper.orderByDesc(MjBill::getCreateTime);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MjBill> mjBillList = list(wrapper);
        if(ObjectUtil.isNotEmpty(mjBillList)){
            mjBillList.forEach(mjBill -> {

            });
        }
        PageInfo<MjBill> info = new PageInfo<>(mjBillList);
        return PageUtil.PageInfo2MyPage(info);
    }

    @Override
    public boolean delete(Long id) {
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("主键ID不能为空,请核查!");
        }
        return this.removeById(id);
    }

    @Override
    public boolean add(MjBill mjBill) {
        //编码自动生成
        String code = idGenerator.idGenerator("FB");
        mjBill.setBillCode(code);
        mjBill.setCreateId(MoJiCommonUtils.getUserCode());
        mjBill.setUpdateId(MoJiCommonUtils.getUserCode());
        mjBill.setCreateTime(new Date());
        mjBill.setUpdateTime(new Date());
        return this.save(mjBill);
    }

    @Override
    public boolean edit(MjBill mjBill) {
        MjBill mjBill1=this.getById(mjBill.getId());
        if(mjBill1 ==null){
            throw new RuntimeException("数据不存在,请核查!");
        }
        BeanUtils.copyProperties(mjBill,mjBill1);
        mjBill1.setUpdateId(MoJiCommonUtils.getUserCode());
        mjBill1.setUpdateTime(new Date());
        return this.updateById(mjBill1);
    }

    @Override
    public MjBillVo detail(Long id) {
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("主键ID不能为空,请核查!");
        }
        MjBillVo mjBillVo=new MjBillVo();
        MjBill mjbill=this.getById(id);
        BeanUtils.copyProperties(mjbill,mjBillVo);

        LambdaQueryWrapper<MjUser> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MjUser::getUserCode,mjbill.getUserCode());
        MjUser mjUser=mjUserService.getOne(wrapper);
        if(mjUser !=null){
            mjBillVo.setUserMobile(mjUser.getMobile());
            mjBillVo.setUserEmail(mjUser.getEmail());
            mjBillVo.setUserType(mjUser.getUserType());
        }
        String address = mjbill.getAddress();
        if(ObjectUtil.isNotEmpty(address)){
            StringBuilder stringBuilder=new StringBuilder();
            if(address.split("/")!=null&&address.split("/").length>0)
            {
                String[] split = address.split("/");

                for (int i = 0; i < split.length; i++) {
                    LambdaQueryWrapper<GdArea> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(GdArea::getAreaCode,split[i]);
                    String areaName = gdAreaService.getOne(wrapper1).getAreaName();
                    stringBuilder.append(areaName);

                }
                mjBillVo.setAddressName(stringBuilder.toString());
            }
        }

        return mjBillVo;
    }

    @Override
    public boolean completeBill(CompleteBillDto dto) {
        MjBill mjBill=this.getById(dto.getId());
        if(mjBill ==null){
            throw new RuntimeException("数据不存在,请核查!");
        }
        mjBill.setBillUrl(dto.getBillUrl());
        mjBill.setBillStatus(1);
        //更新订单未开票
        MjOrder mjOrder=mjOrderService.getOne(new LambdaQueryWrapper<MjOrder>()
                .eq(MjOrder::getOrderCode,mjBill.getOrderCode()));
        if(mjOrder !=null){
            mjOrder.setBillStatus(2);
            mjOrderService.updateById(mjOrder);
        }

        //增加消息通知
        SysMessage sysMessage=new SysMessage();
        sysMessage.setReceiveUserId(mjBill.getCreateId());
        sysMessage.setSendUserId(MoJiCommonUtils.getUserCode());
        sysMessage.setMarkAsRead(0);
        sysMessage.setMessageTitle("发票提醒");
        //消息类型 1-发票提醒 2-下单成功 3-待支付提醒4-超时未支付 5-工单回复 6-工单完结 7-服务到期提醒
        sysMessage.setMessageType("1");
        sysMessage.setMessageCenter("尊敬的用户您好：您于"+ DateUtils.formatDate(mjBill.getCreateTime(),DateUtils.DATE_FORMAT_EXP1) +"申请的发票已经开票完成，" +
                "订单编号为："+mjBill.getOrderCode()+"，请您注意邮箱查收，如有疑问请联系客服！");
        sysMessage.setBillNo(mjBill.getOrderCode()+"");
        sysMessage.setBillTypeCode("1");
        sysMessage.setCreateId(MoJiCommonUtils.getUserCode());
        sysMessage.setUpdateId(MoJiCommonUtils.getUserCode());
        sysMessage.setCreateTime(new Date());
        sysMessage.setUpdateTime(new Date());
        sysMessageService.add(sysMessage);
        return this.updateById(mjBill);
    }
}
